package com.example.score_reception.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.score_reception.entity.*;
import com.example.score_reception.entity.Class;
import com.example.score_reception.service.*;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
/**
 * @author shenrui
 * @date 2021/9/30
 * @description 老师的行为
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    TeacherService teacherService;
    @Autowired
    ClassTeacherService classTeacherService;
    @Autowired
    ClassService classService;
    @Autowired
    CourseService courseService;
    @Autowired
    ClassStudentService classStudentService;
    @Autowired
    StudentService studentService;
    @Autowired
    StudentScoreService studentScoreService;
    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 页面跳转
     */
    @RequestMapping("/teacher_login")
    public String student() {
        //已经登录用户无需登录
        if(!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) {
            return "redirect:/teacher/teacher_main";
        } else {
            return "teacher/teacher_login";
        }
    }
    @RequestMapping("/teacher_main")
    public String teacherMain() {
        return "/teacher/teacher_main";
    }
    @RequestMapping("/teacher_class_list")
    public  String teacherCourseList() {
        return "/teacher/teacher_class_list";
    }
    @RequestMapping("/teacher_score_list")
    public  String teacherScoreList() {
        return "/teacher/teacher_score_list";
    }
    @RequestMapping("/teacher_password")
    public  String teacherPassword() {
        return "/teacher/teacher_password";
    }
    @RequestMapping("/teacher_class_detail")
    public String teacherClassDetail() {
        return "/teacher/teacher_class_detail";
    }
    @RequestMapping("/teacher_class_score")
    public String teacherClassScore() {
        return "teacher/teacher_class_score";
    }

    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 跳转修改密码
     */
    @RequestMapping("do_teacher_password")
    public String doTeacherPassword(HttpSession session) {
        Teacher teacher = (Teacher) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute("teacherInfo",teacher);
        return "redirect:/teacher/teacher_password";
    }
    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 修改密码
     */
    @RequestMapping("/submit_teacher_password")
    public String submitTeacherPassword(Teacher teacher, Model model) {
        //填入信息不能为空
        if (StringUtils.isNullOrEmpty(teacher.getTeacherPassword())) {
            model.addAttribute("stuMsg", "密码不能为空");
            return "redirect:/teacher/teacher_password";

        }
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = bcryptPasswordEncoder.encode(teacher.getTeacherPassword());
        teacher.setTeacherPassword(hashPass);
        //进行更新
        Boolean bool = teacherService.updateById(teacher);
        if (bool) {
            return "redirect:/teacher/teacher_main";
        } else {
            model.addAttribute("teacherMsg", "修改失败");
            return "redirect:/teacher/teacher_password";
        }
    }

    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 老师查看自己的班级
     */
    @RequestMapping("/do_teacher_class_list")
    public  String doTeacherClassList(HttpSession session) {
        Teacher teacher = (Teacher) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Class> classList = new ArrayList<>();
        Class teacherClass;
        List<ClassTeacher> classTeacherList = classTeacherService.list(new LambdaQueryWrapper<ClassTeacher>().eq(ClassTeacher::getTeacherId,teacher.getTeacherId()));
        if(classTeacherList !=null) {
            for(int i = 0 ; i < classTeacherList.size() ; i++) {
                teacherClass = classService.getOne(new LambdaQueryWrapper<Class>().eq(Class::getId,classTeacherList.get(i).getClassId()));
                teacherClass.setCourseName(courseService.getOne(new LambdaQueryWrapper<Course>().eq(Course::getCourseId,teacherClass.getCourseId())).getCourseName());
                classList.add(teacherClass);
            }
        }
        session.setAttribute("classList",classList);
        return "redirect:/teacher/teacher_class_list";
    }


    /**
     *@description 跳转到班级详情页面
     * @return String
     */
    @GetMapping("/class_detail_jump/{id}")
    public String classDetailJump(@PathVariable("id") Long id, HttpSession session) {
        Long score;
        List<Student> studentList = new ArrayList<>();
        StudentScore studentScore;
        Long classId = classService.getById(id).getClassId();
        List<ClassStudent> classStudentList = classStudentService.list(new LambdaQueryWrapper<ClassStudent>().eq(ClassStudent::getClassId,classId));
        for(int i = 0 ; i < classStudentList.size() ; i++) {
            Student student = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getStuId, classStudentList.get(i).getStudentId()));
            studentList.add(student);
        }
        for(int i = 0 ; i < studentList.size() ; i++) {
            studentScore = studentScoreService.getOne(new LambdaQueryWrapper<StudentScore>().eq(StudentScore::getStudentId,studentList.get(i).getStuId())
                    .eq(StudentScore::getScoreStatus,1).eq(StudentScore::getClassId,id));
            if(studentScore != null) {
                score = studentScore.getScore();
                studentList.get(i).setScore(score);
            }
        }
        session.setAttribute("studentList",studentList);
        return "redirect:/teacher/teacher_class_detail";
    }

    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 老师查看需要批改成绩的班级
     */
    @RequestMapping("/do_teacher_score_list")
    public  String doTeacherScoreList(HttpSession session) {
        Teacher teacher = (Teacher) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Class> classList = new ArrayList<>();
        Class teacherClass;
        List<ClassTeacher> classTeacherList = classTeacherService.list(new LambdaQueryWrapper<ClassTeacher>().eq(ClassTeacher::getTeacherId,teacher.getTeacherId()));
        if(classTeacherList !=null) {
            for(int i = 0 ; i < classTeacherList.size() ; i++) {
                teacherClass = classService.getOne(new LambdaQueryWrapper<Class>().eq(Class::getId,classTeacherList.get(i).getClassId()));
                teacherClass.setCourseName(courseService.getOne(new LambdaQueryWrapper<Course>().eq(Course::getCourseId,teacherClass.getCourseId())).getCourseName());
                if(teacherClass.getStatus() == 0) {
                    classList.add(teacherClass);
                }
            }
        }
        session.setAttribute("classList",classList);
        return "/teacher/teacher_score_list";
    }

    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 老师查看需要批改班级成绩的学生
     */
    @GetMapping("/class_score_jump/{id}")
    public String classScoreJump(@PathVariable("id") Long id, HttpSession session) {
        Long score;
        List<Student> studentList = new ArrayList<>();
        StudentScore studentScore;
        Long classId = classService.getById(id).getClassId();
        List<ClassStudent> classStudentList = classStudentService.list(new LambdaQueryWrapper<ClassStudent>().eq(ClassStudent::getClassId,classId));
        for(int i = 0 ; i < classStudentList.size() ; i++) {
            Student student = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getStuId, classStudentList.get(i).getStudentId()));
            student.setClassId(id);
            student.setClassStatus(classStudentList.get(i).getStatus());
            studentList.add(student);
        }
        for(int i = 0 ; i < studentList.size() ; i++) {
            studentScore = studentScoreService.getOne(new LambdaQueryWrapper<StudentScore>().eq(StudentScore::getStudentId,studentList.get(i).getStuId())
                    .eq(StudentScore::getScoreStatus,1).eq(StudentScore::getClassId,id));
            if(studentScore != null) {
                score = studentScore.getScore();
                studentList.get(i).setScore(score);
            }
        }
        session.setAttribute("studentList",studentList);
        return "/teacher/teacher_class_score";
    }

    /**
     * @author shenrui
     * @date 2021/9/30
     * @description 批改学生成绩
     */
    @Transactional
    @RequestMapping("/do_teacher_score")
    public String doTeacherScore(Student student, HttpSession session) throws Exception {
        StudentScore studentScore = new StudentScore();
        ClassStudent classStudent;
        try{
            if(student.getScore() != null) {
                classStudent = classStudentService.getOne(new LambdaQueryWrapper<ClassStudent>().eq(ClassStudent::getClassId,student.getClassId()).eq(ClassStudent::getStudentId,student.getStuId()));
                studentScore.setScore(student.getScore());
                studentScore.setStudentId(student.getStuId());
                studentScore.setClassId(student.getClassId());
                studentScore.setScoreStatus(0L);
                studentScoreService.save(studentScore);
                classStudent.setStatus(1L);
                classStudentService.updateById(classStudent);
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();

        }
        return "redirect:/teacher/teacher_class_score";
    }
}
